import 'dart:io';
import 'package:fate_blind_box/ui/account/scan/scan_main_controller.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../im/group/add_new_group_page.dart';
import '../../../theme/theme_color.dart';

class ScanMainPage extends StatefulWidget {
  Function? refreshBlock;
  bool isAddGroup = false;

  ScanMainPage({Key? key, this.refreshBlock, this.isAddGroup = false})
      : super(key: key);

  @override
  State<ScanMainPage> createState() => _ScanMainPageState();
}

class _ScanMainPageState extends State<ScanMainPage>
    with SingleTickerProviderStateMixin {
  ScanMainController controller = Get.put(ScanMainController());
  late AnimationController animationController;
  late Animation _animation;

  // 主视图
  Widget _buildView(BuildContext context) {
    return Stack(
      children: [
        MobileScanner(
          fit: BoxFit.cover,
          controller: controller.cameraController,
          onScannerStarted: (capture) {},
          onDetect: (capture) {
            final List<Barcode> barcodes = capture.barcodes;
            String? codeString;
            for (final barcode in barcodes) {
              if (barcode.rawValue!.isNotEmpty) {
                debugPrint('Barcode found! ${barcode.rawValue}');
                codeString = barcode.rawValue!;
                break;
              }
            }
            getCodeFormPic(codeString ?? '');
          },
        ),
        AnimatedBuilder(
          builder: (cxt, child) {
            return Container(
              // width: 5, 设了宽度之后，动画没了，不知道为啥
              margin: EdgeInsets.fromLTRB(
                  37.5, 50.h + _animation.value, 37.5, controller.bottomHeight),
              child: child,
            );
          },
          animation: animationController,
          child: Image.asset("images/scan/scanning_line.png",
              color: ThemeColor.appColor,
              fit: BoxFit.fill,
              width: double.infinity),
        ),
        getTorchLightView(),
      ],
    );
  }

  //手电筒和文字布局
  Widget getTorchLightView() {
    return GestureDetector(
      onTap: () {
        controller.cameraController.toggleTorch();
      },
      child: Center(
        child: Container(
          width: 70.w,
          height: controller.torchLightHeight,
          margin: EdgeInsets.only(
              top: 1.sh -
                  44 -
                  ScreenUtil().statusBarHeight -
                  controller.bottomHeight -
                  controller.torchLightHeight -
                  ScreenUtil().bottomBarHeight),
          //alignment: Alignment.center,
          child: ValueListenableBuilder(
            valueListenable: controller.cameraController.torchState,
            builder: (context, state, child) {
              controller.torchState = state as TorchState;
              String torchIconStr = state == TorchState.off
                  ? 'images/scan/torch_light_off.png'
                  : 'images/scan/torch_light_on.png';
              return Image.asset(
                torchIconStr,
                width: controller.torchLightHeight,
              );
            },
          ),
        ),
      ),
    );
  }

  //拿到二维码里面的信息以后逻辑
  void getCodeFormPic(String codeString) {
    animationController.stop();
    if (codeString.isNotEmpty) {
      List<String> strList = codeString.split('invite_code=');
      if (strList.isNotEmpty) {
        String lastStr = strList.last;
        if(widget.isAddGroup){
          Get.to(AddNewGroupPage(groupId: lastStr,));
        }else{
          if (widget.refreshBlock != null) {
            widget.refreshBlock!(lastStr);
          }
          Get.back();
        }

      }
    } else {
      toast('未识别到能匹配到二维码，扫码失败');
      Future.delayed(const Duration(seconds: 2)).then((value) {
        Get.back();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        AppWidget.navTitleBar(
          bgColor: Colors.black,
          title: '扫一扫',
          childWidget: _buildView(context),
        ),
        Positioned(
          child: GetBuilder(
              id: controller.permissionViewId,
              builder: (ScanMainController mainController) {
                return Visibility(
                  visible: mainController.isShow,
                  child: GestureDetector(
                    onTap: () {
                      mainController.isShow = false;
                      mainController.update([controller.permissionViewId]);
                    },
                    child: Container(
                      width: 1.sw,
                      height: 1.sh,
                      color: const Color.fromRGBO(0, 0, 0, 0.2),
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.only(
                                left: 30, top: ScreenUtil().statusBarHeight),
                            width: 1.sw,
                            height: 90,
                            color: Colors.white,
                            child: const Text(
                              '相机权限说明\n扫一扫功能，用于添加好友和进群',
                              style: TextStyle(fontSize: 16),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              }),
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
      reverseDuration: const Duration(seconds: 3),
    );

    //Tween
    //.1创建位移的tween，值必须是double类型
    _animation = Tween(
            begin: 0.0,
            end: 1.sh -
                ScreenUtil().statusBarHeight -
                44 -
                controller.bottomHeight -
                50.h -
                controller.torchLightHeight)
        .animate(animationController);
    //开始动画
    animationController.repeat();
    if(CommonConfig.isHuaWeiPermission){
      showPermissionView();
    }
  }

  void showPermissionView() {
    isOpenCameraPermission().then((value) {
      controller.isShow = value;
      controller.update([controller.permissionViewId]);
    });
  }

  Future<bool> isOpenCameraPermission() async {
    var status = await Permission.camera.status;
    if (status.isGranted) {
      return false;
    }
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
}
